//! 内存子系统初始化

use lazy_static::lazy_static;
use std::sync::{Arc, Mutex};
use crate::core::error::{FFIError, FFIResult};
use super::cache::three_level_cache::{CacheLevel, CachePolicy, ThreeLevelCache};
use super::ai::config_optimizer::ConfigOptimizer;
use super::allocator::radix_tree_allocator::RadixTreeAllocator;
use super::async_io::AsyncIOScheduler;

// 系统内存池大小（1GB）
const SYSTEM_MEMORY_POOL_SIZE: usize = 1024 * 1024 * 1024;

// 系统显存池大小（512MB）
const SYSTEM_VIDEO_MEMORY_POOL_SIZE: usize = 512 * 1024 * 1024;

// 内存对齐要求（4096字节）
const MEMORY_ALIGNMENT: usize = 4096;

// L1缓存容量
const L1_CACHE_CAPACITY: usize = 100;

// L2缓存容量
const L2_CACHE_CAPACITY: usize = 500;

// L3缓存容量
const L3_CACHE_CAPACITY: usize = 2000;

/// 系统内存池全局实例
lazy_static! {
    pub static ref SYSTEM_MEMORY_POOL: Arc<Mutex<RadixTreeAllocator>> = Arc::new(Mutex::new(
        RadixTreeAllocator::new("system_memory_pool", SYSTEM_MEMORY_POOL_SIZE, MEMORY_ALIGNMENT)
    ));
}

/// 系统显存池全局实例
lazy_static! {
    pub static ref SYSTEM_VIDEO_MEMORY_POOL: Arc<Mutex<RadixTreeAllocator>> = Arc::new(Mutex::new(
        RadixTreeAllocator::new("system_video_memory_pool", SYSTEM_VIDEO_MEMORY_POOL_SIZE, MEMORY_ALIGNMENT)
    ));
}

/// 系统配置优化器全局实例
lazy_static! {
    pub static ref CONFIG_OPTIMIZER: Arc<ConfigOptimizer> = Arc::new(ConfigOptimizer::new());
};

/// 全局异步I/O调度器实例
lazy_static! {
    pub static ref ASYNC_IO_SCHEDULER: Arc<Mutex<Option<AsyncIOScheduler>>> = Arc::new(Mutex::new(None));
}

/// 系统三级缓存全局实例
lazy_static! {
    pub static ref SYSTEM_THREE_LEVEL_CACHE: Arc<ThreeLevelCache<Vec<u8>>> = Arc::new(
        ThreeLevelCache::new(L1_CACHE_CAPACITY, L2_CACHE_CAPACITY, L3_CACHE_CAPACITY, CachePolicy::LRU)
    );
}

/// 初始化内存子系统
pub fn init_memory_subsystem() -> FFIResult<()> {
    // 初始化内存池
    if let Ok(mut memory_pool) = SYSTEM_MEMORY_POOL.lock() {
        memory_pool.reset_stats();
        log::info!("System memory pool initialized: {} bytes", memory_pool.size());
    } else {
        return Err(FFIError::InitializationFailed("Failed to initialize system memory pool".to_string()));
    }
    
    // 初始化显存池
    if let Ok(mut video_memory_pool) = SYSTEM_VIDEO_MEMORY_POOL.lock() {
        video_memory_pool.reset_stats();
        log::info!("System video memory pool initialized: {} bytes", video_memory_pool.size());
    } else {
        return Err(FFIError::InitializationFailed("Failed to initialize system video memory pool".to_string()));
    }
    
    // 初始化三级缓存
    let mut system_cache = SYSTEM_THREE_LEVEL_CACHE.clone();
    
    // 为三级缓存设置AI优化器
    Arc::get_mut(&mut system_cache).map(|cache| {
        cache.set_optimizer(CONFIG_OPTIMIZER.clone());
        log::info!("System three-level cache initialized with AI optimizer");
    });
    
    // 设置优化器性能指标权重
    CONFIG_OPTIMIZER.set_performance_weight("memory_usage", 0.2);
    CONFIG_OPTIMIZER.set_performance_weight("video_memory_usage", 0.2);
    CONFIG_OPTIMIZER.set_performance_weight("cache_hit_rate", 0.35);
    CONFIG_OPTIMIZER.set_performance_weight("response_time", 0.15);
    CONFIG_OPTIMIZER.set_performance_weight("fragmentation", 0.1);
    
    // 初始化异步I/O调度器
    if let Ok(mut scheduler) = ASYNC_IO_SCHEDULER.lock() {
        // 创建并初始化异步I/O调度器（20个并发任务，8个工作线程）
        let mut async_io_scheduler = AsyncIOScheduler::new(20, 8);
        if let Err(err) = async_io_scheduler.initialize() {
            log::error!("Failed to initialize async I/O scheduler: {}", err);
        } else {
            *scheduler = Some(async_io_scheduler);
            log::info!("Async I/O scheduler initialized successfully");
        }
    }
    
    log::info!("Memory subsystem initialization completed successfully");
    Ok(())
}

/// 分配系统内存
pub fn allocate_system_memory(size: usize) -> FFIResult<u64> {
    if let Ok(mut memory_pool) = SYSTEM_MEMORY_POOL.lock() {
        memory_pool.allocate(size)
    } else {
        Err(FFIError::LockFailed("Failed to lock system memory pool".to_string()))
    }
}

/// 释放系统内存
pub fn deallocate_system_memory(address: u64) -> FFIResult<()> {
    if let Ok(mut memory_pool) = SYSTEM_MEMORY_POOL.lock() {
        memory_pool.deallocate(address)
    } else {
        Err(FFIError::LockFailed("Failed to lock system memory pool".to_string()))
    }
}

/// 分配系统显存
pub fn allocate_system_video_memory(size: usize) -> FFIResult<u64> {
    if let Ok(mut video_memory_pool) = SYSTEM_VIDEO_MEMORY_POOL.lock() {
        video_memory_pool.allocate(size)
    } else {
        Err(FFIError::LockFailed("Failed to lock system video memory pool".to_string()))
    }
}

/// 释放系统显存
pub fn deallocate_system_video_memory(address: u64) -> FFIResult<()> {
    if let Ok(mut video_memory_pool) = SYSTEM_VIDEO_MEMORY_POOL.lock() {
        video_memory_pool.deallocate(address)
    } else {
        Err(FFIError::LockFailed("Failed to lock system video memory pool".to_string()))
    }
}

/// 从三级缓存获取数据
pub fn get_from_system_cache(key: &str) -> FFIResult<Option<Vec<u8>>> {
    SYSTEM_THREE_LEVEL_CACHE.get(key)
}

/// 将数据插入到三级缓存
pub fn insert_to_system_cache(key: &str, value: Vec<u8>, level: CacheLevel) {
    SYSTEM_THREE_LEVEL_CACHE.insert(key, value, level);
}

/// 从三级缓存移除数据
pub fn remove_from_system_cache(key: &str) -> bool {
    SYSTEM_THREE_LEVEL_CACHE.remove(key)
}

/// 优化系统配置
pub fn optimize_system_config(
    memory_usage: f64, 
    video_memory_usage: f64, 
    cache_hit_rate: f64, 
    response_time: f64, 
    fragmentation: f64
) -> FFIResult<()> {
    // 获取优化建议
    let recommendations = CONFIG_OPTIMIZER.optimize_config(
        memory_usage, 
        video_memory_usage, 
        cache_hit_rate, 
        response_time, 
        fragmentation
    )?;
    
    // 应用优化建议
    for (key, value) in recommendations.iter() {
        log::info!("Applying optimization: {} = {}", key, value);
        
        // 根据建议类型执行不同的优化操作
        match key.as_str() {
            "memory_policy" => {
                // 应用内存策略优化
                log::info!("Memory policy updated to: {}", value);
            },
            "video_memory_policy" => {
                // 应用显存策略优化
                log::info!("Video memory policy updated to: {}", value);
            },
            "cache_policy" => {
                // 应用缓存策略优化
                log::info!("Cache policy updated to: {}", value);
                // 优化三级缓存配置
                CONFIG_OPTIMIZER.optimize_three_level_cache(&SYSTEM_THREE_LEVEL_CACHE);
            },
            "fragmentation_policy" => {
                // 应用碎片化优化
                log::info!("Fragmentation policy updated to: {}", value);
            },
            "deep_learning_mode" => {
                // 设置深度学习模式
                let enabled = value == "aggressive" || value == "explore" || value == "exploit";
                CONFIG_OPTIMIZER.toggle_deep_learning(enabled);
                log::info!("Deep learning mode updated to: {}", value);
            },
            _ => {
                // 其他优化建议
                log::info!("Other optimization applied: {} = {}", key, value);
            },
        }
    }
    
    Ok(())
}

/// 获取系统内存使用情况
pub fn get_system_memory_usage() -> FFIResult<(usize, usize, f64)> {
    if let Ok(memory_pool) = SYSTEM_MEMORY_POOL.lock() {
        Ok((
            memory_pool.allocated_size(),
            memory_pool.available_size(),
            memory_pool.usage()
        ))
    } else {
        Err(FFIError::LockFailed("Failed to lock system memory pool".to_string()))
    }
}

/// 获取系统显存使用情况
pub fn get_system_video_memory_usage() -> FFIResult<(usize, usize, f64)> {
    if let Ok(video_memory_pool) = SYSTEM_VIDEO_MEMORY_POOL.lock() {
        Ok((
            video_memory_pool.allocated_size(),
            video_memory_pool.available_size(),
            video_memory_pool.usage()
        ))
    } else {
        Err(FFIError::LockFailed("Failed to lock system video memory pool".to_string()))
    }
}

/// 获取系统缓存统计信息
pub fn get_system_cache_stats() -> (usize, usize, f32) {
    SYSTEM_THREE_LEVEL_CACHE.get_stats()
}

/// 获取系统缓存层级统计信息
pub fn get_system_cache_level_stats(level: CacheLevel) -> (usize, usize, f32) {
    SYSTEM_THREE_LEVEL_CACHE.get_level_stats(level)
}

/// 添加系统缓存预加载项
pub fn add_system_cache_preload_item(key: &str, value: Vec<u8>, priority: u8) {
    SYSTEM_THREE_LEVEL_CACHE.add_preload_item(key, value, priority);
}

/// 执行系统缓存预加载
pub fn execute_system_cache_preload() {
    SYSTEM_THREE_LEVEL_CACHE.preload();
}

/// 获取系统缓存预加载队列长度
pub fn get_system_cache_preload_queue_length() -> usize {
    SYSTEM_THREE_LEVEL_CACHE.get_preload_queue_length()
}

/// 获取配置优化器
pub fn get_config_optimizer() -> Arc<ConfigOptimizer> {
    CONFIG_OPTIMIZER.clone()
}

/// 获取系统内存池
pub fn get_system_memory_pool() -> Arc<Mutex<RadixTreeAllocator>> {
    SYSTEM_MEMORY_POOL.clone()
}

/// 获取系统显存池
pub fn get_system_video_memory_pool() -> Arc<Mutex<RadixTreeAllocator>> {
    SYSTEM_VIDEO_MEMORY_POOL.clone()
}

/// 获取系统三级缓存
pub fn get_system_three_level_cache() -> Arc<ThreeLevelCache<Vec<u8>>> {
    SYSTEM_THREE_LEVEL_CACHE.clone()
}

/// 获取异步I/O调度器
pub fn get_async_io_scheduler() -> FFIResult<Arc<Mutex<Option<AsyncIOScheduler>>>> {
    Ok(ASYNC_IO_SCHEDULER.clone())
}

/// 关闭内存子系统
pub fn shutdown_memory_subsystem() -> FFIResult<()> {
    // 关闭异步I/O调度器
    if let Ok(mut scheduler) = ASYNC_IO_SCHEDULER.lock() {
        if let Some(mut sched) = scheduler.take() {
            if let Err(err) = sched.shutdown() {
                log::error!("Failed to shutdown async I/O scheduler: {}", err);
            }
        }
    }
    
    log::info!("Memory subsystem shutdown completed");
    Ok(())
}